package cn.wildfirechat.app.tools;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import cn.wildfirechat.app.LoginResponseVO;
import cn.wildfirechat.app.RedisKeyConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class RedisOpUtils {
    @Autowired
    StringRedisTemplate stringRedisTemplate;

    public void setNonce(String nonce){
        stringRedisTemplate.opsForValue().set(RedisKeyConstants.HTTP_NONCE_KEY+nonce,"1",60, TimeUnit.SECONDS);
    }

    public String getNonce(String nonce){
        return stringRedisTemplate.opsForValue().get(RedisKeyConstants.HTTP_NONCE_KEY+nonce);
    }

    public void setUserToken(String uid,String token){
        stringRedisTemplate.opsForValue().set(RedisKeyConstants.USER_TOKEN_KEY+uid,token,604800, TimeUnit.SECONDS);
    }

    public String getToken(String uid){
        return stringRedisTemplate.opsForValue().get(RedisKeyConstants.USER_TOKEN_KEY+uid);
    }

    public String getVcode(String phone){
//        public final static String USER_PHONE_VCODE_KEY = "user:phone:vcode:";
        return stringRedisTemplate.opsForValue().get(RedisKeyConstants.USER_PHONE_VCODE_KEY+phone);
    }

    public boolean checkToken(String uid,String token){
        String oldToken = stringRedisTemplate.opsForValue().get(RedisKeyConstants.USER_TOKEN_KEY+uid);
        if(StrUtil.isEmpty(token)|| StrUtil.isEmpty(oldToken)){
            return false;
        }
        if(token.equals(oldToken))return true;
        return false;
    }

    public void clearIndexRecommendGameList(){
        stringRedisTemplate.delete(RedisKeyConstants.INDEX_GAME_RECOMMEND_LIST_KEY);
    }

    public LoginResponseVO getUserInfo(Long uid){
        return JSONUtil.toBean(stringRedisTemplate.opsForValue().get(RedisKeyConstants.USER_INFO+uid),LoginResponseVO.class);
    }


}
